package com.leesche.zcsp.node.web.controller.web.operation;

import com.leesche.zcsp.node.utils.web.PagingResult;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.WebUtils;
import com.leesche.zcsp.node.utils.web.gernerator.UUIDGenerateUtil;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.web.user.ChildUserController;
import com.leesche.zcsp.node.web.model.SysAppInfo;
import com.leesche.zcsp.node.web.model.SysNotice;
import com.leesche.zcsp.node.web.service.SysAppInfoService;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDeviceDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryAppInfoCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDeviceCondition;
import com.leesche.zcsp.node.web.service.impl.data.read.SysAppInfoDto;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.Map;

/**
 * @author Jerry Chan
 * @version V1.0
 *          ************ * Jerry Chan: * 2016/12/16 16:34: * 创建该类并实现业务逻辑: *********
 * @Title: UploadController.java
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2016/12/16 16:34
 */
@Controller
@RequestMapping("/web/release")
public class AppController {

    private final static Logger logger = Logger.getLogger(AppController.class);

    @Autowired
    private PrivilegeService privilegeService;
    @Autowired
    private SysAppInfoService sysAppInfoService;

    private static final String SHOW_VIEW = "web/uploadAPK/listView";

    private static final String ADD_VIEW = "web/uploadAPK/addView";

    @RequestMapping(value = "/showview", method = RequestMethod.GET)
    public String listView() {
        return SHOW_VIEW;
    }

    @RequestMapping(value = "/addview", method = RequestMethod.GET)
    public String addView() {
        return ADD_VIEW;
    }


    @ResponseBody
    @RequestMapping(value = "/list.json", method = RequestMethod.GET)
    public Map<String, Object> listJson(final QueryAppInfoCondition condition) {
        PagingResult<SysAppInfoDto> pagingResult = sysAppInfoService.findAllByPage(condition);
        Map<String, Object> json = WebResult.buildOf(pagingResult).toMap();
        return json;
    }

    /**
     * @param app app安装包
     * @Title: uploadUserLogo
     * @Description: TODO(发布APP文件)
     * @author Jerry Chen
     * @date 2016年10月22日 上午3:05:21
     */
    @ResponseBody
    @RequestMapping(value = "/uplaodapp", method = RequestMethod.POST)
    public Map<String, Object> uploadUserLogo(@RequestParam(value = "app", required = false) MultipartFile app, String version, String changecontent) {
        try {
            if (app.isEmpty()) {
                return WebResult.failure("请选择APP文件").toMap();
            }

            String fileName = app.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf("."));

            if (!WebUtils.checkIsApplication(extName)
                    || !app.getContentType().matches("application.*")) {
                return WebResult.failure("上传的必须是apk、ipa、pxl文件").toMap();
            }

            QueryAppInfoCondition condition = new QueryAppInfoCondition();
            condition.setVersion(version);
            SysAppInfo appInfo = sysAppInfoService.findAppByLatestVersion(condition);
            if(appInfo != null){
                return WebResult.failure(version + "版APP已经存在，请确认版本号").toMap();
            }


            String apppath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_APK_DIRECTORY);

            //String logoname = fileName + extName;
            //String logoname = Constants.APP_NAME + extName;
            String appname = Constants.APP_NAME +  "-" + version + extName;
            condition.setVersion(null);
            condition.setAppname(appname);
            appInfo = sysAppInfoService.findAppByLatestVersion(condition);
            if(appInfo != null){
                return WebResult.failure("["+appname + "]已经存在，请确认后重新发布。").toMap();
            }

            File appfile = new File(apppath, appname);

            if (!appfile.exists()) {
                appfile.mkdirs();
            }

            app.transferTo(appfile);

            SysAppInfo sysAppInfo = new SysAppInfo();

            sysAppInfo.setVersion(version);
            sysAppInfo.setChangecontent(changecontent);
            sysAppInfo.setReleaseurl(SessionManager.getWebServerURL() + Constants.SYSTEM_TMAGE_APK_DIRECTORY + "/" + appname);
            sysAppInfo.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            sysAppInfo.setUpdatetime(new Date());

            if (sysAppInfoService.insertSelective(sysAppInfo) > 0)
                return WebResult.success().info("apk发布成功").toMap();
            else
                return WebResult.failure("apk发布失败").toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return WebResult.failure("上传的apk无法识别").toMap();
        }

    }


}
